package m3u8

import (
	"errors"
	"onvif_server/internal/utils"
	"strings"
	"time"
)

type Ts struct {
	raw      string
	t        time.Time
	baseName string
}

func (m *Ts) Time() time.Time {
	return m.t
}

func (m *Ts) String() string {
	return m.raw
}

func (m *Ts) BaseName() string {
	return m.baseName
}

// ParseM3u8TsName 解析这个路径，年/月/日/年月日时分秒.ts 格式
// ts: 2023/03/29/20230329101051.ts
func ParseM3u8TsName(ts string, loc *time.Location) (mt Ts, err error) {
	if loc == nil {
		loc = time.Local
	}
	ts = strings.TrimSpace(ts)
	if !strings.HasSuffix(ts, ".ts") {
		err = errors.New("not have .ts suffix")
		return
	}
	arr := strings.Split(ts, "/")
	l := len(arr)
	if l < 4 {
		err = errors.New("ts fail")
		return
	}
	mt.raw = ts
	mt.baseName = strings.TrimSuffix(arr[l-1], ".ts")
	mt.t, err = time.ParseInLocation(utils.FormatDatetime1, mt.baseName, loc)
	return
}

func ParseTsDatetime(ts string) string {
	ts = strings.TrimSpace(ts)
	if !strings.HasSuffix(ts, ".ts") {
		return ""
	}
	arr := strings.Split(ts, "/")
	l := len(arr)
	if l < 4 {
		return ""
	}
	return strings.TrimSuffix(arr[l-1], ".ts")
}
